package cn.zs.supply.common.core.security.simple;


import cn.zs.supply.common.annotation.LoginMethod;
import cn.zs.supply.common.annotation.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
public class FunctionImp implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private SpringContextUtil springContextUtil;
    private ContextRefreshedEvent event;
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        this.event=event;
    }
    public Object  serviceUse(Use use){
        Object object=null;
        try {
            // 获取上下文
            ApplicationContext context = this.event.getApplicationContext();
            // 获取所有beanNames
            String[] beanNames = context.getBeanNamesForType(Object.class);
            for (String beanName : beanNames) {
                LoginService loginService = context.findAnnotationOnBean(beanName,LoginService.class);
                //判断该类是否含有HelloClass注解
                if (loginService != null) {
                    Method[] methods = context.getBean(beanName).getClass().getDeclaredMethods();
                    for (Method method : methods) {
                        //判断该方法是否有HelloMethod注解
                        if (method.isAnnotationPresent(LoginMethod.class)) {
                            String  name=context.getBean(beanName).getClass().getName();
                            int one = name.lastIndexOf(".");
                            name=name.substring((one+1),name.length());
                            name=toLowerCaseFirstOne(name);
                            Object obj=springContextUtil.getBean(name,context.getBean(beanName).getClass());
                            object = method.invoke(obj, use);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;

    }


    /**
     * 首字母转小写
     * @param s
     * @return
     */
    public static String toLowerCaseFirstOne(String s){
        if(Character.isLowerCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
    }
}

